import sys
import os
import re
import ConfigParser
import globalvar
from optparse import OptionParser
import struct
import stat
import binascii

Version = 0x0        
RawImagePkg = 0x1
RawImagePkgBP = 0x2
FSUpdatePkg = 0x4

def unsigned(n):
    return n & 0xFFFFFFFF        

def write_data(outfd,filename,version):
    if filename != None:
        size = os.stat(filename)[stat.ST_SIZE];
        inf = open(filename,'rb')
        alldata = inf.read(size)  
        outfd.write(struct.pack('I',version))
        outfd.write(struct.pack('I', size+4))
        crcsize=binascii.crc32(alldata)
        crcsize= unsigned(crcsize)
        outfd.write(struct.pack('I',crcsize))
        outfd.write(alldata)
        inf.close()       
        
def upk_gen(apfile,bpfile,fsfile,outfile):
    #write the version
    outf=open(outfile,'wb')
    
    outf.write(struct.pack('I',Version))
    outf.write(struct.pack('I',128))
    
    outf.write("DM1.2")
    for i in range(0,123):
        outf.write(struct.pack('B',0))    

    write_data(outf,apfile,RawImagePkg)    
    write_data(outf,bpfile,RawImagePkgBP)
    write_data(outf,fsfile,FSUpdatePkg)
    outf.close()
    if globalvar.dmlogging:
        globalvar.dmlogging.debug('upk_gen(apfile=%s,bpfile=%s,fsfile=%s,outfile=%s)'%(apfile,bpfile,fsfile,outfile))    
    
    return 0
    

def main(*argv):
    """Generate the diff package using the """
    if argv:
        argv = list(argv)
    else:
        argv = sys.argv[1:]
        
    usage = "usage: fs_diff -i [infile]"    
    parser = OptionParser(usage=usage)    
    
    parser.add_option("-b", "--apfile", dest="apfile",type="string",help="ap diff file  ")
    parser.add_option("-n", "--bpfile", dest="bpfile",type="string",help="bp diff file ")
    parser.add_option("-f", "--fsfile", dest="fsfile",type="string",help="fs diff file ")
    parser.add_option("-o", "--outfile", dest="outfile",type="string",help="out file ")

    (options, args) = parser.parse_args(args=argv)
    apfile = bpfile = fsfile = outfile = None
    if options.apfile:
        apfile = os.path.abspath(options.apfile)
    if options.bpfile:    
        bpfile = os.path.abspath(options.bpfile)
    if options.fsfile:    
        fsfile = os.path.abspath(options.fsfile)
    if options.outfile:    
        outfile = os.path.abspath(options.outfile)
    
    
    ret = upk_gen(apfile,bpfile,fsfile,outfile)
       
    print ret
        
if __name__ == "__main__":
    main()
    